// 用于配置对应路由
let express = require('express')
let articlequery = require('../api/article_query')
let router = express.Router()
router.use(express.json());
router.use(express.urlencoded({
    extended: true
}));

//获取所有文章信息
router.get('/', function (req, res) {
    res.redirect('/articles'); // 重定向
});
router.get('/articles', (req, res) => {
    articlequery.getall(function (rec) {
        res.json(rec).end();
    });
});

//获取指定name的文章信息 {通过id}
router.get('/articles/:article_id', function (req, res) {
    var article_id = parseInt(req.params.article_id);
    articlequery.get(article_id, function (rec) {
        res.json(rec).end();
    });
    console.log(article_id);
});

//获取指定id的文章信息的原来数据 {通过id}
router.get('/articles/origin/:article_id', function (req, res) {
    var article_id = parseInt(req.params.article_id);
    articlequery.getOrigin(article_id, function (rec) {
        res.json(rec).end();
    });
    console.log(article_id);
});
//使用POST方法添加文章信息
router.post('/articles', function (req, res) {
    var reqbody = req.body;
    console.log(reqbody);
    var arr = [];
    //遍历JSON数据中所有的值
    for (var key in reqbody) {
        arr.push(reqbody[key]);
    }
    articlequery.add([
        reqbody.cover,
        reqbody.auother_id,
        reqbody.title,
        reqbody.pubulish_time,
        reqbody.category_id,
        reqbody.commnet_id,
        reqbody.state_id,
        reqbody.content
    ], function (rec) {
        res.json(rec).end();
    });
});
function fmObjToArr(data) {
    let arr = [];
    arr.push(data.cover);
    arr.push(data.auother_id);
    arr.push(data.title);
    arr.push(data.pubulish_time);
    arr.push(data.category_id);
    arr.push(data.commnet_id);
    arr.push(data.state_id);
    arr.push(data.content);
    arr.push(data.id);
    return arr;
}
//使用PUT方法修改文章信息 TODO
router.put('/articles_corr/:article_id', function (req, res) {
    var article_id = parseInt(req.params.article_id);
    var reqbody = req.body;
    //先判断ID是否有效，再执行修改操作
    articlequery.getOrigin(article_id, function (rec) {
        console.log(rec,"rec");
        if (rec.length == 0) {
            res.status(404).json({
                msg: '指定ID的文章不存在！'
            });
        } else {
            const newRequstBody = {
                ...rec[0],
                ...reqbody
            }
            articlequery.update(fmObjToArr(newRequstBody), function (rec) {
                res.json(rec).end();
            });
        }
    });
});

//使用DELETE方法删除文章信息
router.delete('/articles/:id', function (req, res) {
    var article_id = parseInt(req.params.id);
    // var reqbody = req.body;
    //先判断ID是否有效，再执行删除操作
    articlequery.get(article_id, function (rec) {
        if (rec.length == 0) {
            res.status(404).json({
                msg: '指定ID的文章不存在！'
            });
        } else {
            articlequery.del(article_id, function (p) {
                res.json(rec).end();
            });
        }
    });
});
module.exports = router